<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <PageForm
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-locationNo>
                <el-input
                  v-model="formInfo.data.locationNo"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择过渡货位号"
                >
                  <template #append>
                    <el-icon @click="selectLocationNo"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </PageForm>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <PageTable
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :tab-index="true"
                  :check-box="false"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isDynamic="true"
                >
                  <template v-slot:col-downShelfQty="scope">
                    <el-form-item
                      class="margin-bottom"
                      v-if="
                        scope.row.codeType === 1 || scope.row.codeType === 4
                      "
                    >
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item">
                            <el-form-item
                              v-if="scope.$index >= 0"
                              :prop="`data.${scope.$index}.largeUnitQty`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: $validate.positiveAndZero,
                                        trigger: 'blur',
                                      },
                                    ]
                                  : {}
                              "
                            >
                              <el-input-number
                                v-model.lazy="scope.row.largeUnitQty"
                                style="width: 100%; margintop: 18px"
                                clearable
                                controls-position="right"
                                :precision="
                                  scope.row.qtyOperateMode === 0 ||
                                  scope.row.qtyOperateMode === 2
                                    ? 0
                                    : systemConfig.qty_show_precision
                                "
                                :min="0"
                                :disabled="
                                  (scope.row.goodsLocationCalcQty ||
                                  0 > scope.row.pendExportCalcQty
                                    ? scope.row.pendExportCalcQty
                                    : scope.row.goodsLocationCalcQty || 0) === 0
                                "
                                :max="largeMax(scope.row)"
                                @change="
                                  changeLarge(
                                    $event,
                                    scope.row,
                                    `data.${scope.$index}.largeUnitQty`
                                  )
                                "
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div>
                          </div>
                          <div
                            v-if="
                              scope.row.unitConvertCoefficient > 1 &&
                              scope.row.qtyOperateMode === 2
                            "
                            class="page-table-input-number-item"
                          >
                            <el-form-item>
                              <el-input-number
                                v-model.lazy="scope.row.smallUnitQty"
                                style="width: 100%; margintop: 18px"
                                clearable
                                controls-position="right"
                                :precision="0"
                                :min="0"
                                :disabled="
                                  (scope.row.goodsLocationCalcQty ||
                                  0 > scope.row.pendExportCalcQty
                                    ? scope.row.pendExportCalcQty
                                    : scope.row.goodsLocationCalcQty || 0) === 0
                                "
                                :max="smallMax(scope.row)"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div>
                          </div>
                        </div>
                      </div>
                    </el-form-item>
                    <div
                      v-if="
                        scope.row.codeType === 2 || scope.row.codeType === 3
                      "
                    >
                      {{ $fn.qtyFormatter(scope.row.downShelfQty) }}
                    </div>
                  </template>
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <SelectCargoSpace
      v-if="selectLocationNoInfo.visible"
      v-model:show-dialog="selectLocationNoInfo.visible"
      :check-box="false"
      v-model:query="selectLocationNoInfo.query"
      :highlight-row="true"
      :check-lock="true"
      :save-empty="true"
      :showDepot="false"
      @callback="selectLocationNoCallBack"
    />
    <Individual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      :leftTableKey="individualInfo.leftTableKey"
      :rightTableKey="individualInfo.rightTableKey"
      :leftQuery="individualInfo.leftQuery"
      :rowData="individualInfo.row"
      :details="individualInfo.details"
      :showPrice="$permission('wmsExportStockOrder:price')"
      @callback="individualCallback"
    ></Individual>
  </div>
</template>

<script setup name="wmsExportStockOrderModify">
import { getCoreSystemConfigAll } from '@/api/core'
import {
  getWmsExportStockById,
  quickCreateShelfTask,
  getWmsExportStockDetailCustomizeListAll,
  getExportStockOrderSelectByGoodsLocation,
} from '@/api/wms'
import { getCustomizeSetting } from '@/api/customize'
import Individual from './individual'
import moment from 'moment'

const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'exportId'])
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const formRefs = ref(null)
//表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: 'wms出库单号',
      value: 'orderNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '出库仓库',
      value: 'depotName',
      type: 'input',
      disabled: true,
    },
    {
      label: '出库部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '入库仓库',
      value: 'storeDepotName',
      type: 'input',
      disabled: true,
    },
    {
      label: '入库部门',
      value: 'storeDeptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '出库类型',
      value: 'type',
      type: 'select-model',
      disabled: true,
      code: 'wms_export_type',
    },
    {
      label: '过渡货位号',
      value: 'locationNo',
      type: 'slot',
      disabled: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    locationNo: [
      { required: true, message: '请选择过渡货位号', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.exportId,
      },
    },
    queryParams: {},
  },
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  baseData: [],
  sysGroup: [],
  summaryFieldList: [
    { value: 'downShelfQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: individual,
        show: true,
        ifRender: ifRenderValue,
      },
    ],
  },
})
const individualInfo = ref({
  visible: false,
  leftQuery: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      orgId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      price: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      storeBatchNumber: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      batchNumber: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      productionDate: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      validityDate: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      goodsLocationId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  leftTableKey:
    'wmsExportStockModifySingleLeft-com.slip.spd.entity.vo.wms.WmsShelfStockVO',
  rightTableKey:
    'wmsExportStockModifySingleRight-com.slip.spd.entity.vo.wms.WmsShelfStockVO',
  details: {},
  row: {},
  index: 0,
})
const selectLocationNoInfo = ref({
  visible: false,
  query: {
    locationType: 2,
    status: 1,
    depotId: '',
  },
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    // 更新父组件visible
    proxy.$emit('update:visible', newValue)
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canAddProduct = computed(() => {
  return formInfo.value.data.depotId && formInfo.value.data.deptId
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      tableInfo.value.data.forEach((row) => {
        if (row.codeType === 1 || row.codeType === 4) {
          let smallUnitQty = parseFloat(row.smallUnitQty || 0)
          let unitConvertCoefficient = parseFloat(
            row.unitConvertCoefficient || 1
          )
          let largeUnitQty = parseFloat(row.largeUnitQty || 0)
          let downShelfCalcQty = proxy.$fn.accAdd(
            proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
            smallUnitQty
          )
          let downShelfQty = proxy.$fn.accDiv(
            downShelfCalcQty,
            unitConvertCoefficient
          )
          row['downShelfCalcQty'] = downShelfCalcQty
          row['downShelfQty'] = downShelfQty
          row.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(downShelfCalcQty, parseFloat(row.price)),
            unitConvertCoefficient
          )

          if (row.details && row.details.length) {
            row.details[0].downShelfQty = downShelfQty
            row.details[0].downShelfCalcQty = downShelfCalcQty
            row.details[0].largeUnitQty = largeUnitQty
            row.details[0].smallUnitQty = smallUnitQty
            row.details[0].sumAmount = row.sumAmount
          }
        }
      })
      console.log(val)
    }
  },
  { deep: true }
)
function onlyShowOption() {
  let options = proxy.$store.state.permission.dict['wms_export_type'] || []
  if (options.length) {
    options = options.filter((item) => item.code == 2).map((item) => item.code)
  }
  return options
}
function largeMax(row) {
  let maxCalcQty =
    row.goodsLocationCalcQty || 0 > row.pendExportCalcQty
      ? row.pendExportCalcQty
      : row.goodsLocationCalcQty || 0
  if (row.qtyOperateMode === 2) {
    return parseInt(maxCalcQty / row.unitConvertCoefficient)
  } else {
    return maxCalcQty
  }
}
function smallMax(row) {
  let maxCalcQty =
    row.goodsLocationCalcQty || 0 > row.pendExportCalcQty
      ? row.pendExportCalcQty
      : row.goodsLocationCalcQty || 0
  let largeUnitQty = parseInt(maxCalcQty / row.unitConvertCoefficient)
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(maxCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let maxCalcQty =
    row.goodsLocationCalcQty || 0 > row.pendExportCalcQty
      ? row.pendExportCalcQty
      : row.goodsLocationCalcQty || 0
  let largeUnitQty = parseInt(maxCalcQty / row.unitConvertCoefficient)
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(maxCalcQty % row.unitConvertCoefficient)
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
  if(row.details && row.details.length) {
    row.details[0].qty = e
    row.details[0].calcQty = e
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function ifRenderValue(row) {
  return (
    formInfo.value.data.goodsLocationId &&
    (row.codeType === 2 || row.codeType === 3)
  )
}

function getMain() {
  getWmsExportStockById(props.exportId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      selectLocationNoInfo.value.query.depotId = resp.data.depotId
    }
  })
}

function getList() {
  //修改请求明细信息
  getWmsExportStockDetailCustomizeListAll(filterInfo.value.query).then(
    (resp) => {
      if (resp && resp.success && resp.data && resp.data.length) {
        let data = proxy.$fn.deepClone(resp.data)
        tableInfo.value.data = resp.data.filter((item) => {
          item.pendExportQty = proxy.$fn.deepClone(item.calcQty)
          item.pendExportCalcQty = proxy.$fn.deepClone(item.qty)
          item.downShelfQty = 0
          item.downShelfCalcQty = 0
          item.largeUnitQty = 0
          item.smallUnitQty = 0
          item.sumAmount = 0
          return item
        })
        tableInfo.value.baseData = data.filter((item) => {
          item.pendExportQty = item.calcQty
          item.pendExportCalcQty = item.qty
          return item
        })
      }
    }
  )
}
function individual(row, index) {
  individualInfo.value.visible = true
  individualInfo.value.row = row
  individualInfo.value.details = row.details || []
  individualInfo.value.index = index
  let ids = []
  if (row.details && row.details.length) {
    ids = row.details.map((item) => item.cargoStockId)
  }
  individualInfo.value.leftQuery.queryMap.depotId.value =
    formInfo.value.data.depotId
  individualInfo.value.leftQuery.queryMap.goodsLocationId.value =
    formInfo.value.data.goodsLocationId
  individualInfo.value.leftQuery.queryMap.id.value = ids.length
    ? ids.toString()
    : ''
  if (tableInfo.value.sysGroup.length) {
    tableInfo.value.sysGroup.forEach((key) => {
      if (key === 'price') {
        individualInfo.value.leftQuery.queryMap[key].value = row[key] || 0
      } else {
        individualInfo.value.leftQuery.queryMap[key].value = row[key] || ''
      }
    })
  }
}
function individualCallback(data) {
  let index = individualInfo.value.index
  tableInfo.value.data[index].details = data
  let unitConvertCoefficient =
    tableInfo.value.data[index].unitConvertCoefficient || 1
  let downShelfCalcQty = 0
  let largeUnitQty = 0
  let smallUnitQty = 0
  data.forEach((item) => {
    downShelfCalcQty = proxy.$fn.accAdd(
      item.downShelfCalcQty || 0,
      downShelfCalcQty
    )
    largeUnitQty = proxy.$fn.accAdd(item.largeUnitQty || 0, largeUnitQty)
    smallUnitQty = proxy.$fn.accAdd(item.smallUnitQty || 0, smallUnitQty)
  })
  tableInfo.value.data[index].downShelfCalcQty = downShelfCalcQty
  tableInfo.value.data[index].largeUnitQty = largeUnitQty
  tableInfo.value.data[index].smallUnitQty = smallUnitQty
  tableInfo.value.data[index].downShelfQty = proxy.$fn.accDiv(
    downShelfCalcQty,
    unitConvertCoefficient
  )
  tableInfo.value.data[index].sumAmount = proxy.$fn.accDiv(
    proxy.$fn.accMul(downShelfCalcQty, tableInfo.value.data[index].price || 0),
    unitConvertCoefficient
  )
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const newDetails = tableInfo.value.data.filter(
      (row) => row.productId && row.downShelfQty
    )
    if (!newDetails.length) {
      proxy.$message({
        message: '请添加有效的产品',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let details = proxy.$fn.filterBlacklist(newDetails)
    //校验过期产品是否准许出库
    getCoreSystemConfigAll().then((resp) => {
      if (resp && resp.success) {
        let find = resp.data.find(
          (item) => item.systemConfigCode === 'allow_expire_out'
        )
        if (find) {
          let expire = validateExpire(newDetails)
          if (find.value === '1') {
            if (expire) {
              proxy
                .$confirm(expire + ',是否继续?', '警告', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  dangerouslyUseHTMLString: true,
                })
                .then(() => {
                  const data = formInfo.value.data
                  data.mergeDetails = details
                  quickCreateShelfTask(data).then((resp) => {
                    if (resp && resp.success) {
                      showDialog.value = false
                      proxy.$emit('returnModify', false)
                    }
                  })
                  return
                })
                .catch(() => {
                  return
                })
            } else {
              const data = formInfo.value.data
              data.mergeDetails = details
              quickCreateShelfTask(data).then((resp) => {
                if (resp && resp.success) {
                  showDialog.value = false
                  proxy.$emit('returnModify', false)
                }
              })
            }
          } else {
            if (expire) {
              proxy.$alert(expire + '，不允许出库！', '操作提示', {
                confirmButtonText: '确定',
                dangerouslyUseHTMLString: true,
              })
              return
            } else {
              const data = formInfo.value.data
              data.mergeDetails = details
              quickCreateShelfTask(data).then((resp) => {
                if (resp && resp.success) {
                  showDialog.value = false
                  proxy.$emit('returnModify', false)
                }
              })
            }
          }
        } else {
          const data = formInfo.value.data
          data.mergeDetails = details
          quickCreateShelfTask(data).then((resp) => {
            if (resp && resp.success) {
              showDialog.value = false
              proxy.$emit('returnModify', false)
            }
          })
        }
      }
    })
  })
}
function validateExpire(list = []) {
  let currentDate = moment().format('YYYY-MM-DD')
  let msg = ''
  list.forEach((item, index) => {
    if (item.validityDate && moment(item.validityDate).isBefore(currentDate)) {
      msg = msg + `第【${index + 1}】行产品【${item.commonName}】已过期，<br>`
    }
  })
  return msg
}

//选择过渡货位号
function selectLocationNo() {
  selectLocationNoInfo.value.visible = true
}
function selectLocationNoCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.value.data.locationNo = data.locationNo
    formInfo.value.data.goodsLocationId = data.id
    getExportStockOrderSelectByGoodsLocationList()
  } else {
    formInfo.value.data.locationNo = ''
    formInfo.value.data.goodsLocationId = ''
    tableInfo.value.data = []
  }
}
function getExportStockOrderSelectByGoodsLocationList() {
  let params = {
    depotId: formInfo.value.data.depotId,
    detailList: tableInfo.value.baseData,
    goodsLocationId: formInfo.value.data.goodsLocationId,
  }
  getExportStockOrderSelectByGoodsLocation(params).then((res) => {
    if (res && res.success) {
      if (res.data && res.data.length) {
        res.data.forEach((item) => {
          if (item.codeType === 2 || item.codeType === 3) {
            let smallUnitQty = parseFloat(item.smallUnitQty || 0)
            let unitConvertCoefficient = parseFloat(
              item.unitConvertCoefficient || 1
            )
            let largeUnitQty = parseFloat(item.largeUnitQty || 0)
            let downShelfCalcQty = proxy.$fn.accAdd(
              proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
              smallUnitQty
            )
            let downShelfQty = proxy.$fn.accDiv(
              downShelfCalcQty,
              unitConvertCoefficient
            )
            item['downShelfCalcQty'] = downShelfCalcQty
            item['downShelfQty'] = downShelfQty
            item.sumAmount = proxy.$fn.accDiv(
              proxy.$fn.accMul(downShelfCalcQty, parseFloat(item.price)),
              unitConvertCoefficient
            )
            if (item.details && item.details.length) {
              item.details.forEach((el) => {
                el.downShelfCalcQty = proxy.$fn.deepClone(el.calcQty || 0)
                el.qty = proxy.$fn.accDiv(
                  el.calcQty || 0,
                  el.unitConvertCoefficient || 1
                )
                el.downShelfQty = proxy.$fn.deepClone(el.qty || 0)
              })
            }
          }
        })
      }
      tableInfo.value.data = res.data
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'wmsExportStockDetailModify-com.slip.spd.entity.vo.wms.WmsExportStockOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      let arr = []
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          arr.push(key)
        }
      }
      tableInfo.value.sysGroup = arr
      if (props.exportId) {
        getMain()
        getList()
      }
    }
  })
}

let obj = {
  downShelfQty: {
    label: '数量',
    value: 'downShelfQty',
    type: 'slot',
    minWidth: '250px',
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('wmsExportStockOrder:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('wmsExportStockOrder:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('wmsExportStockOrder:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  locationTypeValue: {
    label: '货位属性',
    value: 'locationTypeValue',
    asValue: 'locationType',
    componentType: 'select-model',
    code: 'goods_location_type',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
})
</script>

<style scoped lang="scss">
:deep(.PageTable) > .el-table {
  overflow: hidden;
}
</style>
